package net.javaonfly.core.dispatch;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Map;

import net.javaonfly.core.exception.JofException;

public class HandlerRoute implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1571700234264569807L;

	private String pkg;

	private Class controller;

	private Method action;

	private String template;

	private String pathString;

	private HandlerRoute(String pkg, Class controller, Method action,
			String template) {
		super();
		this.pkg = pkg;
		this.controller = controller;
		this.action = action;
		this.template = template;
		StringBuffer sbf = new StringBuffer("/");
		sbf.append(pkg);
		sbf.append("/");
		sbf.append(this.getController().getSimpleName().toLowerCase());
		sbf.append("/");
		sbf.append(this.getAction().getName().toLowerCase());
		pathString = sbf.toString();
	}

	public Method getAction() {
		return action;
	}

	public void setAction(Method action) {
		this.action = action;
	}

	public Class getController() {
		return controller;
	}

	public void setController(Class controller) {
		this.controller = controller;
	}

	public String getTemplate() {
		return template;
	}

	public void setTemplate(String template) {
		this.template = template;
	}

	/**
	 * @param url
	 * @return
	 */
	public boolean matchUrl(String url) {
		return url.startsWith(this.toString());
	}

	@Override
	public String toString() {
		return pathString;
	}

	/**
	 * @param url
	 * @param pkg
	 * @return
	 * @throws JofException
	 */
	public static HandlerRoute resolve(String url, String pkg)
			throws JofException {
		String[] params = url.split("/");
		String op=null;
		if(params.length>3){
			op=params[3];
		}else{
			op="index";
		}
		Class c;
		Method d;
		try {
			String a = params[2].substring(0, 1).toUpperCase();
			String b = params[2].substring(1);
			c = Class.forName(pkg + "." + params[1] + "." + a + b);
			d = c.getDeclaredMethod(op, String.class, Map.class,
					Map.class, Map.class);
		} catch (Exception e) {
			throw new JofException("can not resolve url: " + url, e);
		}
		return new HandlerRoute(params[0],c, d, "/WEB-INF/jsp/" + params[1] + "/"
				+ params[2]+ "/"
				+ op + ".jsp");
	}

	public String getPkg() {
		return pkg;
	}

	public void setPkg(String pkg) {
		this.pkg = pkg;
	}

}
